package com.erp.ae.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.erp.ae.domain.AeMsgSave;
import com.erp.ae.domain.bo.AeMsgSaveBo;
import com.erp.ae.service.IAeSaveOrderService;
import com.ruoyi.common.core.domain.R;
import com.erp.ae.utils.AeApiUtils;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 从速卖通拉取AE新订单
 * @Author: j.zh
 * @Date: 2024/5/11
 * @Version: 4.0.0
 **/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/erp/erpSaveOrder")
public class AePullNewOrderController {
    private final IAeSaveOrderService iAeSaveOrderService;
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;
    private static final String AE_MSG_KEY = "AE_MSG_ORDER_LIST";

    /**
     * @param storeUserName   cn码
     * @param createDateStart
     * @param createDateEnd
     * @param orderId
     * @return
     * @Description: 从速卖通获取订单
     * @Author: j.zh
     * @Date: 2024/5/9
     * @Version: 4.0.0
     **/
    @GetMapping("/pullOrdersFromAliExpress")
    public R<Object> pullOrdersFromAliExpress(@Param("storeUserName") String storeUserName,
                                              @Param("createDateStart") String createDateStart,
                                              @Param("createDateEnd") String createDateEnd,
                                              @Param("orderId") String orderId) {
        /**
         * 获取订单逻辑：
         * 1、根据店铺及相关信息，获取店铺订单列表
         * 2、根据有订单的店铺，获取对应的店铺中已有的订单列表
         * 3、比对订单，如果有，则忽略，如果没有，则放入新增列表
         * 4、放入新增列表之前，将原始订单进行mq数据分发，处理相关业务逻辑
         **/

        /** 1、判断店铺授权情况 **/
        List<ErpSellerStoreEmpower> storeEmpowerList = new ArrayList<>();
        ErpSellerStoreEmpower storeEmpower = null;
        if (Objects.isNull(storeUserName)) {
            // 所有店铺
            R<Object> storeEmpowerObject = remoteSellerStoreService.getEmpowerStore();
            if (storeEmpowerObject.getCode() != 200) {
                return R.fail("获取店铺授权信息失败");
            }
            String storeEmpowerString = JSONObject.toJSONString(storeEmpowerObject.getData());
            storeEmpowerList = JSONArray.parseArray(storeEmpowerString, ErpSellerStoreEmpower.class);
        } else {
            // 单个店铺
            R<Object> storeEmpowerObject = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(storeUserName);
            if (storeEmpowerObject.getCode() != 200) {
                return R.fail("获取店铺授权信息失败");
            }
            String storeEmpowerString = JSONObject.toJSONString(storeEmpowerObject.getData());
            storeEmpower = JSONObject.parseObject(storeEmpowerString, ErpSellerStoreEmpower.class);
            storeEmpowerList.add(storeEmpower);
        }

        /** 2、根据店铺拉取新订单 **/
        StringBuffer pullLogBuffer = new StringBuffer();
        if (orderId != null && !orderId.equals("")) {
            // 单订单
            pullLogBuffer.append(iAeSaveOrderService.pullOrdersFromAliExpress(orderId, storeUserName,
                    AeApiUtils.getToken(storeEmpower.getId()),0).getData());
        } else {
            for (ErpSellerStoreEmpower store : storeEmpowerList) {
                // 1、获取店铺新订单ID
                List<Long> newOrderIdList = iAeSaveOrderService.pullNewOrderIdListFromAliExpress(store.getStoreUserName(), AeApiUtils.getToken(store.getId()), createDateStart, createDateEnd);
                // 2、获取店铺新订单
                String orderIds = String.join(",", newOrderIdList.stream().map(String::valueOf).toArray(String[]::new));
                pullLogBuffer.append(iAeSaveOrderService.pullOrdersFromAliExpress(orderIds, store.getStoreUserName(),
                        AeApiUtils.getToken(store.getId()),0).getData());
                pullLogBuffer.append("\n");
            }
        }

        return R.ok(pullLogBuffer.toString());
    }


    /**
     * 速卖通推送增量订单
     *
     * @Version: 4.0.0
     */
    @GetMapping("/aePushOrdersInfo")
    public R<Object> aePushOrdersInfo() {
        //从缓存中获取信息
        String orderMap = RedisUtils.getCacheObject(AE_MSG_KEY);
        if (orderMap.equals("")){
            return R.ok("没有待执行的订单");
        }
        return iAeSaveOrderService.aePushOrdersInfo(orderMap);
    }


//    /**
//     * 拉取单个订单
//     * @param map
//     * @return
//     * 4.0.0以后合并至pullOrdersFromAliExpress方法统一入口
//     */
//    @PostMapping("/queryOrderFromAeByOrderId")
//    public R<Object> queryOrderFromAeByOrderId(@RequestBody Map<String, Object> map) {
//        String storeId = (String) map.get("storeId");
//        String accessToken = AeApiUtils.getToken(storeId);
//        Long orderId = (Long) map.get("orderId");
//        return iAeSaveOrderService.queryOrderFromAeByOrderId(accessToken,orderId);
//    }

//    /**
//     * 新版 从速卖通拉取订单
//     *
//     * @param map
//     * @return
//     * 4.0.0以后合并至pullOrdersFromAliExpress方法统一入口
//     */
//    @PostMapping("/getNewOrderFromAe")
//    public R<Object> getNewOrderFromAe(@RequestBody Map<String, Object> map) {
//        String sellerId = (String) map.get("sellerId");
//        String accessToken = AeApiUtils.getToken(sellerId);
//        String createDateStart = (String) map.get("createDateStart");
//        String createDateEnd = (String) map.get("createDateEnd");
//        String currentpage = (String) map.get("currentpage");
//        Integer pageSize = (Integer) map.get("pageSize");
//
//        return iAeSaveOrderService.getNewOrderFromAe(sellerId,accessToken,createDateStart,createDateEnd,currentpage,pageSize);
//
//    }

    // 新新版，从速卖通拉取订单 4.0.0以后合并至pullOrdersFromAliExpress方法统一入口
//    @PostMapping("/pullOrdersFromAliExpress")
//    public R<Object> pullOrdersFromAliExpress(@RequestBody Map<String, Object> map) {
//        return iAeSaveOrderService.pullOrdersFromAliExpress(map);
//    }


}
